<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Welcome extends Controller
{

    public function action_index()
    {
        $pictures = ORM::factory('image')->limit(12)->find_all();
        $count = ORM::factory('image')->find_all()->count();
        $content = View::factory('welcome/index')->bind('pictures', $pictures)->bind('count', $count);
        $this->response->body($content);
    }

    public function action_add()
    {
        $picture = ORM::factory('image');
        $message = '';
        if ($post = $this->request->post()) {

            $picture->text = Security::xss_clean($post['desc']);

            if (isset($_FILES['picture']['name'])
                && !empty($_FILES['picture']['name'])
            ) {
                $name = uniqid(NULL, TRUE);
                $ext = strtolower(pathinfo($_FILES['picture']['name'], PATHINFO_EXTENSION));

                if ($image = Upload::save($_FILES['picture'], $name . '.' . $ext, 'media/upload/')) {

                    Helper::image_resize($image, 150, 200, 'media/upload/' . $name . '_min.' . $ext);

                    $picture->file_path = 'media/upload/' . $name . '.' . $ext;
                    $picture->file_path_min = 'media/upload/' . $name . '_min.' . $ext;
                }
            }

            $picture->save();
            $message = 'Фото добавлено';
        }

        $content = View::factory('welcome/add')->bind('message', $message);
        $this->response->body($content);
    }

    public function action_ajax()
    {
        if ($this->request->is_ajax()) {
            $offset = (int)Arr::get($_POST, 'offset', 0);
            $pictures = DB::query(Database::SELECT, 'SELECT * FROM images limit '.$offset.',12')->execute()->as_array();
            die(json_encode($pictures));
        }
        else throw new HTTP_Exception_404('Page not found');
    }

} // End Welcome
